#include <bits/stdc++.h>
#define ll long long
#define mem(f, x) memset(f, x, sizeof(f))
#define pii pair<int, int>
#define fi first
#define se second
#define mk(x, y) make_pair(x, y)
#define pk push_back
using namespace std;
const int M = 40;
const int N = 30;
const int MOD = 1e9 + 7;
const ll INF = 1e18 + 50;
int m, n;
int main()
{
    int t;
    int at[12], bt[12];
    scanf("%d", &t);
    while (t--)
    {
        mem(at, 0);
        mem(bt, 0);
        map<int, pii> mpa;
        map<int, pii> mpb;
        int x;
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                scanf("%d", &x);
                mpa[x] = mk(i, j);
            }
        }
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                scanf("%d", &x);
                mpb[x] = mk(i, j);
            }
        }
        int up = 31;
        bool flaga = 0, flagb = 0;
        int ans = 0;
        for (int i = 0; i < 25; i++)
        {
            scanf("%d", &x);
            pii p = mpa[x];
            at[p.fi] += 1 << p.se;
            if (at[p.fi] == up)
                flaga = 1;
            at[5 + p.se] += 1 << p.fi;
            if (at[5 + p.se] == up)
                flaga = 1;
            if (p.fi == p.se)
            {
                at[10] += 1 << p.fi;
                if (at[10] == up)
                    flaga = 1;
            }
            if (p.fi + p.se == 4)
            {
                at[11] += 1 << p.fi;
                if (at[11] == up)
                    flaga = 1;
            }

            p = mpb[x];
            bt[p.fi] += 1 << p.se;
            if (bt[p.fi] == up)
                flagb = 1;
            bt[5 + p.se] += 1 << p.fi;
            if (bt[5 + p.se] == up)
                flagb = 1;
            if (p.fi == p.se)
            {
                bt[10] += 1 << p.fi;
                if (bt[10] == up)
                    flagb = 1;
            }
            if (p.fi + p.se == 4)
            {
                bt[11] += 1 << p.fi;
                if (bt[11] == up)
                    flagb = 1;
            }
            if (!ans && (flaga || flagb))
            {
                if (flaga && flagb)
                    ans = 0;
                else if (flaga)
                    ans = 1;
                else if (flagb)
                    ans = 2;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}